
// 主域名
var domain = "http://192.168.1.250/";
// 新增收货地址-接口
var add_address_url = domain+"mb/toUpdateConsigneeAddress.htmls";


$(function(){
    // 按钮-新增地址
	$("#btn_add_address").click(function(){
		// 校验表单数据
		if(verifyForm()){
			saveAddress();
		}
	});
	// 初始化省份
	initProvince();
	//编辑信息加载
	update()
})

function showLoading(flag,msg){
	if(flag){
		$("#loading_bg").show();
		$("#loading_msg").html(msg);
		$("#loading").show();
		window.ontouchmove=function(e){
            e.preventDefault && e.preventDefault();
            e.returnValue=false;
            e.stopPropagation && e.stopPropagation();
            return false;
		}        
	}else{
		window.ontouchmove=function(e){
            e.preventDefault && e.preventDefault();
            e.returnValue=true;
            e.stopPropagation && e.stopPropagation();
            return true;
        }
		$("#loading_bg").hide();
		$("#loading_msg").html("");
		$("#loading").hide();
	}
}

function verifyForm(){
	// 收货人姓名
	var $user_name = $("#user_name").val();
	// 收货人联系方式
	var $mobile = $("#mobile").val();
	// 省
	var $province = $("#label_province").html();
	// 市区
	var $city = $("#label_city").html();
	// 县城
	var $town = $("#label_town").html();
	// 详细地址
	var $address_info = $("#address_info");
	if(null==$user_name || ""==$user_name){
		swal("请填写收货人");
		scroller("user_name",200);
		setTimeout(function(){
			shake($("#user_name"),"red",3);
		}, 2000);
		return false;
	}
	if(null==$mobile || ""==$mobile){
		swal("请填写收货人电话");
		return false;
	}
	if(null==$province || ""==$province || "请选择您所在的省份（市）"==$province){
		swal("请选择所在省份");
		return false;
	}
	if(null==$city || ""==$city || "请选择所在市区"==$city){
		swal("请选择所在市区");
		return false;
	}
	/*if(null==$town || ""==$town || "请选择所在县城"==$town){
		swal("请选择所在县城");
		return false;
	}*/
	if(null==$address_info || ""==$address_info){
		swal("请填写详细街道信息");
		return false;
	}
	return true;
}

function initProvince(){
	var inner_html = "";
	// 页面初始化加载省份
	for(var i = 0;i < area_array.length; i++) {
		var area = area_array[i];
		if(area!=undefined && area!='请选择'){
			inner_html += "<option id=\""+i+"\" value=\""+area+"\">"+area+"</option>";
		}
	}
	$("#select_province").html(inner_html);
	$("#select_province").find("option[value='湖北省']").attr("selected",true);  
	$("#label_province").html("湖北省");
	loadCity(42);
	
	$("#select_province").change(function(){ 
		var o,id;
		var opt = $(this).find('option');
		opt.each(function(i) {
			if (opt[i].selected == true) {
				o = opt[i].innerHTML;
				id = $(opt[i]).attr("id");
			}
		})
		$("#label_province").html(o);
		
		loadCity(id);
	});
}

function loadCity(i){
	// 加载市区
	$("#label_city").html('请选择所在市区');
	var inner_html = "";
	var city_array = sub_array[i];
	for(var j = 0;j < city_array.length; j++) {
		var city = city_array[j];
		if(city!=undefined && city!='请选择'){
			inner_html += "<option id=\""+j+"\" value=\""+city+"\">"+city+"</option>";
		}
	}
	$("#select_city").html(inner_html);
	
	$("#sel_wrap_city").show();
	$("#select_city").unbind();
	$("#select_city").change(function(){ 
		var o,id;
		var opt = $(this).find('option');
		opt.each(function(i) {
			if (opt[i].selected == true) {
				o = opt[i].innerHTML;
				id = $(opt[i]).attr("id");
			}
		})
		$("#label_city").html(o);
		
		loadTown(id);
	});
}

// 加载县城
function loadTown(i){
	var district_array = sub_arr[i];
	if(district_array==undefined){
	$("#sel_wrap_town").hide();
	return false;
	}else{
	$("#label_town").html('请选择所在县城');
	}

	// 加载城镇
	var inner_html = "";
	for(var k = 0; k< district_array.length; k++) {
		var district  = district_array[k];
		if(district!=undefined && district!='请选择'){
			inner_html += "<option id=\""+k+"\" value=\""+district+"\">"+district+"</option>";
		}
	}
	$("#select_town").html(inner_html);
	
	$("#sel_wrap_town").show();
	$("#select_town").unbind();
	$("#select_town").change(function(){ 
		var o;
		var opt = $(this).find('option');
		opt.each(function(i) {
			if (opt[i].selected == true) {
				o = opt[i].innerHTML;
			}
		})
		$("#label_town").html(o);
		
	});
}

// 保存数据
function saveAddress(){
	$id=$("#user_name").attr('uid');
	showLoading(true,"我是飞毛腿,正在狂奔中...");
	$.ajax({
		type: "GET",
		url: add_address_url,
		data: {
			//user_id:100,
			id:$id,
			user_id:$.cookie("user_id"),
			consignee_name : $("#user_name").val(),
			mobile : $("#mobile").val(),
			province : $("#label_province").html(),
			city : $("#label_city").html(),
			town : $("#label_town").html(),
			address_info : $("#address_info").val()
		},
		dataType: "jsonp",
		jsonp: "callbackparam", //服务端用于接收callback调用的function名的参数  
        jsonpCallback: "success_jsonpCallback", //callback的function名称,服务端会把名称和data一起传递回来  
		success: function(json){
			console.debug(json);
			var data = json[0].data;
			var status = data['status'];
			if(1==status){
				showLoading(false, null);
				swal("操作成功");
				location.href="address.html";
			}else{
				showLoading(false, null);
			}
		}
	});
}

function resetForm(){
	$("#user_name").val("");
	$("#mobile").val("");
	$("#label_province").html("请选择您所在的省份（市）");
	$("#label_city").html("请选择所在市区");
	$("#label_town").html("请选择所在县城");
	$("#address_info").val("");
}

/*
 * scroller(el, duration) 锚点(Anchor)间平滑跳转 
 * el : 目标锚点 ID  
 * duration : 持续时间，以毫秒为单位，越小越快
 */
function scroller(el, duration){ 
    if(typeof el != 'object') { el = document.getElementById(el); } 

    if(!el) return; 

    var z = this; 
    z.el = el; 
    z.p = getPos(el); 
    z.s = getScroll(); 
    z.clear = function(){window.clearInterval(z.timer);z.timer=null}; 
    z.t=(new Date).getTime(); 

    z.step = function(){ 
        var t = (new Date).getTime(); 
        var p = (t - z.t) / duration; 
        if (t >= duration + z.t) { 
            z.clear(); 
            window.setTimeout(function(){z.scroll(z.p.y, z.p.x)},13); 
        } else { 
            st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t; 
            sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l; 
            z.scroll(st, sl); 
        } 
    }; 
    z.scroll = function (t, l){window.scrollTo(l, t)}; 
    z.timer = window.setInterval(function(){z.step();},13); 
} 

/*
 * 获取元素信息 
 */
function getPos(e){ 
    var l = 0; 
    var t  = 0; 
    var w = intval(e.style.width); 
    var h = intval(e.style.height); 
    var wb = e.offsetWidth; 
    var hb = e.offsetHeight; 
    while (e.offsetParent){ 
        l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0); 
        t += e.offsetTop  + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0); 
        e = e.offsetParent; 
    } 
    l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0); 
    t  += e.offsetTop  + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0); 
    return {x:l, y:t, w:w, h:h, wb:wb, hb:hb}; 
} 

/*
 * 转换为数字 
 */
function intval(v){ 
    v = parseInt(v); 
    return isNaN(v) ? 0 : v; 
} 

/*
 * 获取滚动条信息 
 */
function getScroll(){ 
    var t, l, w, h; 
    if (document.documentElement && document.documentElement.scrollTop) { 
        t = document.documentElement.scrollTop; 
        l = document.documentElement.scrollLeft; 
        w = document.documentElement.scrollWidth; 
        h = document.documentElement.scrollHeight; 
    } else if (document.body) { 
        t = document.body.scrollTop; 
        l = document.body.scrollLeft; 
        w = document.body.scrollWidth; 
        h = document.body.scrollHeight; 
    } 
    return { t: t, l: l, w: w, h: h }; 
} 

//边框高亮提醒
function shake(ele,cls,times){
	var i = 0,t= false ,o =ele.attr("class")+" ",c ="",times=times||2;
	if(t) return;
	t= setInterval(function(){
		i++;
		c = i%2 ? o+cls : o;
		ele.attr("class",c);
		if(i==2*times){
			clearInterval(t);
			ele.removeClass(cls);
		}
	},200);
};
var $_GET = (function(){
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if(typeof(u[1]) == "string"){
        u = u[1].split("&");
        var get = {};
        for(var i in u){
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();
function utf8to16(str) {  
    var out, i, len, c;  
    var char2, char3;  
  
    out = "";  
    len = str.length;  
    i = 0;  
    while(i < len) {  
         c = str.charCodeAt(i++);  
         switch(c >> 4)  
         {   
           case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:  
             out += str.charAt(i-1);  
             break;  
           case 12: case 13:  
             char2 = str.charCodeAt(i++);  
             out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));  
             break;  
           case 14:  
             char2 = str.charCodeAt(i++);  
             char3 = str.charCodeAt(i++);  
             out += String.fromCharCode(((c & 0x0F) << 12) |  
                ((char2 & 0x3F) << 6) |  
                ((char3 & 0x3F) << 0));  
             break;  
         }  
    }  
  
    return out;  
}  
function update(){
	var $id=$_GET['id'];
	var $user_name=$_GET['user_name'];
	var $mobile=$_GET['mobile'];
	var $province=$_GET['province'];
	var $city=$_GET['city'];
	var $town=$_GET['town'];
	var $address_info=$_GET['address_info'];
	$province=(utf8to16(unescape($province)));
	$city=(utf8to16(unescape($city)));
	$town=(utf8to16(unescape($town)));
	$user_name=(utf8to16(unescape($user_name)));
	$address_info=(utf8to16(unescape($address_info)));
	$("#user_name").attr('uid',$id);
	if($user_name != ""){
		$("#user_name").val($user_name);
	}
	if($mobile != ""){
		$("#mobile").val($mobile);
	}
	if($province != ""){
		$("#label_province").html($province);
	}
	if($city != ""){

		$("#label_city").html($city);
	}
	if($town != ""){
		$("#label_town").html($town);
	}
	if($address_info != ""){
		$("#address_info").val($address_info);
	}
}